package com.newlink.building.userinfo.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.model.PersonalMenuItem

class Module_UserInfo_PersonalMenuAdapter(
    private val context: Context,
    private val items: List<PersonalMenuItem>
) : BaseAdapter() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)

    companion object {
        private const val TYPE_NORMAL = 0
        private const val TYPE_DIVIDER = 1
    }

    override fun getCount(): Int = items.size

    override fun getItem(position: Int): PersonalMenuItem = items[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getViewTypeCount(): Int = 2

    override fun getItemViewType(position: Int): Int {
        return if (items[position].isGroup) TYPE_DIVIDER else TYPE_NORMAL
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val item = getItem(position)
        val viewType = getItemViewType(position)

        val view: View = when (viewType) {
            TYPE_DIVIDER -> {
                convertView ?: inflater.inflate(R.layout.item_personal_divider, parent, false)
            }
            else -> {
                convertView ?: inflater.inflate(R.layout.item_personal_menu, parent, false)
            }
        }

        when (viewType) {
            TYPE_NORMAL -> {
                val iconView = view.findViewById<ImageView>(R.id.iv_menu_icon)
                val titleView = view.findViewById<TextView>(R.id.tv_menu_title)
                val arrowView = view.findViewById<ImageView>(R.id.iv_menu_arrow)
                val badgeView = view.findViewById<ImageView>(R.id.iv_menu_badge)

                iconView.setImageResource(item.iconResId)
                titleView.text = item.title
                arrowView.visibility = if (item.hasArrow) View.VISIBLE else View.GONE
                badgeView.visibility = if (item.hasUnreadBadge) View.VISIBLE else View.GONE
            }
        }

        return view
    }

    override fun isEnabled(position: Int): Boolean {
        return !items[position].isGroup
    }
}